chrome.sidePanel
    .setPanelBehavior({ openPanelOnActionClick: true })
    .catch((error) => console.error(error));


chrome.runtime.onInstalled.addListener(() => {
    console.log('Extension installed');
    chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }).catch(console.error);
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'getImages') {
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            if (tabs[0]) {
                chrome.scripting.executeScript(
                    {
                        target: { tabId: tabs[0].id },
                        func: () => {
                            // 返回去重后的图片信息
                            const images = Array.from(document.images);
                            const seen = new Set();
                            return images
                                .map(img => ({
                                    src: img.src,
                                    width: img.naturalWidth,
                                    height: img.naturalHeight,
                                    alt: img.alt
                                }))
                                .filter(img => {
                                    if (seen.has(img.src)) {
                                        return false;
                                    }
                                    seen.add(img.src);
                                    return true;
                                });
                        },
                    },
                    (results) => {
                        if (chrome.runtime.lastError) {
                            // console.error(chrome.runtime.lastError.message);
                            sendResponse({ images: [] });
                            return;
                        }

                        if (results && results[0]?.result) {
                            sendResponse({ images: results[0].result });
                        } else {
                            sendResponse({ images: [] });
                        }
                    }
                );
            }
        });
        return true; // 允许异步响应
    }
});
